package ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.UiSettings;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.core.SuggestionCity;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.fy.fyzf.R;
import com.fy.fyzf.base.BaseActivity;
import com.fy.fyzf.base.BaseFragment;
import com.fy.fyzf.base.BasePresenter;
import com.fy.fyzf.base.Contans;
import com.fy.fyzf.bean.BuildTypeBean;
import com.fy.fyzf.bean.BuildingDetailBean;
import com.fy.fyzf.bean.HousesListBean;
import com.fy.fyzf.bean.HousesListBean1;
import com.fy.fyzf.glideUtils.GlideUtils;
import com.fy.fyzf.presenter.BuildDetailPresenter;
import com.fy.fyzf.utils.TabLayoutUtils;
import com.fy.fyzf.view.BuildDetailCallBack;
import com.fy.fyzf.weight.MyViewPager;
import com.fy.fyzf.weight.PoiOverlay;
import com.google.android.material.tabs.TabLayout;
import com.stx.xhb.androidx.XBanner;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import ui.adapter.AroundAdapter;
import ui.adapter.BuildAdapter;
import ui.fragment.BuildListFragment;

//楼盘详情
public class BuildingDetailActivity extends BaseActivity<BuildDetailPresenter> implements BuildDetailCallBack, PoiSearch.OnPoiSearchListener {
    @BindView(R.id.xbanner)
    XBanner xbanner;
    @BindView(R.id.tv_build_name)
    TextView tvBuildName;
    @BindView(R.id.tv_location)
    TextView tvLocation;
    @BindView(R.id.tv_location1)
    TextView tvLocation1;
    @BindView(R.id.tv_subway)
    TextView tvSubway;
    @BindView(R.id.tv_all_count)
    TextView tvAllCount;
    @BindView(R.id.recycleView1)
    RecyclerView recycleView1;
    @BindView(R.id.viewpager)
    MyViewPager viewpager;
    @BindView(R.id.tablayout)
    TabLayout tablayout;
    @BindView(R.id.recycleView2)
    RecyclerView recyclerView2;
    private BuildAdapter buildAdapter;
    private int buildindId;
    private AMap map;
    private AroundAdapter aroundAdapter;
    private String[] poiS = new String[]{"150500", "100100", "050000", "160100", "080000"};

    @Override
    protected BuildDetailPresenter createPresenter() {
        return new BuildDetailPresenter(this);
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_building_detail;
    }

    private List<BuildTypeBean> list = new ArrayList<>();
    private List<BaseFragment> fragmentList = new ArrayList<>();

    @Override
    public void initView() {
        super.initView();
        initMap();
        initTabLayout();
        aroundAdapter = new AroundAdapter(this);
        recyclerView2.setLayoutManager(new LinearLayoutManager(this));
        recyclerView2.setAdapter(aroundAdapter);

        tablayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                aroundAdapter.setType(tab.getPosition());
                showMap(2, poiS[tab.getPosition()], "", Double.parseDouble(buildingDetail.getLatitude()), Double.parseDouble(buildingDetail.getLongitude()));
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
//        list.add(new BuildTypeBean("全部",));
        buildAdapter = new BuildAdapter(this);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(RecyclerView.HORIZONTAL);
        recycleView1.setLayoutManager(linearLayoutManager);
        recycleView1.setAdapter(buildAdapter);
        buildAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                buildAdapter.setSelect(position);
                viewpager.setCurrentItem(position, false);
            }
        });
    }

    private void initTabLayout() {
        tablayout.addTab(tablayout.newTab().setText("交通"));
        tablayout.addTab(tablayout.newTab().setText("餐饮"));
        tablayout.addTab(tablayout.newTab().setText("酒店"));
        tablayout.addTab(tablayout.newTab().setText("银行"));
        tablayout.addTab(tablayout.newTab().setText("健身"));
    }

    @Override
    public void initData() {
        super.initData();
        buildindId = getIntent().getIntExtra("housingid", 0);
        mPresenter.getBuildingDetail(buildindId);
    }

    private List<String> imgList = new ArrayList<>();
    private BuildingDetailBean buildingDetail;

    @Override
    public void getBuildingDetailSuccess(BuildingDetailBean buildingDetailBean) {
        buildingDetail = buildingDetailBean;
        if (buildingDetailBean.getFloorDetailsImages().size() == 0) { //图片数据没有的时候 添加一个默认网络图片
            imgList.add(Contans.DEFAULT_IMG_ADDRESS);
        } else {
            for (int i = 0; i < buildingDetailBean.getFloorDetailsImages().size(); i++) {
                imgList.add(buildingDetailBean.getFloorDetailsImages().get(i).getImage());
            }
        }
        xbanner.setData(imgList, null);
        xbanner.loadImage(new XBanner.XBannerAdapter() {
            @Override
            public void loadBanner(XBanner banner, Object model, View view, int position) {
                GlideUtils.loadRoundedCornersImage(imgList.get(position), (ImageView) view, 10);
            }
        });
        xbanner.setCustomPageTransformer(null);
        xbanner.setPointsIsVisible(false);
        tvLocation.setText(buildingDetailBean.getParentAreaName());
        tvSubway.setText(buildingDetailBean.getSubwayName() + "地铁站");

//        showMap(1,null,buildingDetailBean.getSubwayName(),Double.parseDouble(buildingDetailBean.getLatitude()),Double.parseDouble(buildingDetailBean.getLongitude()));
        showMap(2, "150500", "", Double.parseDouble(buildingDetail.getLatitude()), Double.parseDouble(buildingDetail.getLongitude()));

        BuildingDetailBean.CountVoBean countVo = buildingDetailBean.getCountVo();
        setTitleName(buildingDetailBean.getFloorName());
        tvBuildName.setText(buildingDetailBean.getAreaName());
        tvLocation1.setText(buildingDetailBean.getAreaName());

        //0套不展示
        if (countVo.getAllCount() > 0) {
            list.add(new BuildTypeBean("全部", countVo.getAllCount() + "套", -1));
        }
        if (countVo.getLt100() >0 ) {
            list.add(new BuildTypeBean("100m²以下", countVo.getLt100() + "套", 0));
        }
        if (countVo.getGt100lt150() > 0) {
            list.add(new BuildTypeBean("100-150m²", countVo.getGt100lt150() + "套", 1));
        }
        if (countVo.getGt150lt200() >0 ) {
            list.add(new BuildTypeBean("150-200m²", countVo.getGt150lt200() + "套", 2));
        }
        if (countVo.getGt200lt300() >0 ) {
            list.add(new BuildTypeBean("200-300m²", countVo.getGt200lt300() + "套", 3));
        }
        if (countVo.getGt300lt500()  >0 ) {
            list.add(new BuildTypeBean("300-500m²", countVo.getGt300lt500() + "套", 4));
        }
        if (countVo.getGt500lt1000() > 0) {
            list.add(new BuildTypeBean("500-1000m²", countVo.getGt500lt1000() + "套", 5));
        }
        buildAdapter.setNewData(list);
        buildAdapter.setSelect(0);
        for (int i = 0; i < list.size(); i++) {
            fragmentList.add(BuildListFragment.newInstance(buildindId, list.get(i).getId()));
        }
        viewpager.setAdapter(new Myadapter(getSupportFragmentManager()));
    }

    //高德周边检索poi编码
    PoiSearch.Query query;
    private void initMap() {
        map = mapView.getMap();
        UiSettings uiSettings = map.getUiSettings();
        uiSettings.setMyLocationButtonEnabled(false);
        uiSettings.setScrollGesturesEnabled(false);
        uiSettings.setZoomControlsEnabled(false);
        map.setMyLocationEnabled(false);

        map.setOnMapClickListener(new AMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                Intent intent = new Intent(BuildingDetailActivity.this, MapDetailActivity.class);
                intent.putExtra("name", tvLocation.getText().toString());
                startActivity(intent);
            }
        });
    }

    /**
     * @param type 1 名字加经纬度搜索  2 周边搜索
     * @param poiCode
     * @param name
     * @param latitude
     * @param longitude
     */
    private int searchType;

    private void showMap(int type, String poiCode, String name, double latitude, double longitude) {
        searchType = type;
        // 第一个参数表示搜索字符串，第二个参数表示poi搜索类型，第三个参数表示poi搜索区域（空字符串代表全国）
        if (type == 1) {
            query = new PoiSearch.Query(name, "", "杭州");
        } else {
            query = new PoiSearch.Query("", poiCode, "杭州");
        }
        query.setPageSize(10);
        query.setPageNum(0);// 设置查第一页
        query.setCityLimit(true);
        PoiSearch poiSearch = new PoiSearch(this, query);
        poiSearch.setBound(new PoiSearch.SearchBound(new LatLonPoint(latitude,
                longitude), 1000));
        poiSearch.setOnPoiSearchListener(this);
        poiSearch.searchPOIAsyn();
    }

    @Override
    public void getHouseListSuccess(List<HousesListBean1> housesListBean) {

    }

    private PoiResult poiResult;

    @Override
    public void onPoiSearched(PoiResult result, int rCode) {
        if (rCode == AMapException.CODE_AMAP_SUCCESS) {
            if (result != null && result.getQuery() != null) {// 搜索poi的结果
                if (result.getQuery().equals(query)) {// 是否是同一条
                    poiResult = result;
                    // 取得搜索到的poiitems有多少页
                    List<PoiItem> poiItems = poiResult.getPois();// 取得第一页的poiitem数据，页数从数字0开始
                    aroundAdapter.setNewData(poiItems);
                    List<SuggestionCity> suggestionCities = poiResult
                            .getSearchSuggestionCitys();// 当搜索不到poiitem数据时，会返回含有搜索关键字的城市信息
                    if (poiItems != null && poiItems.size() > 0) {
                        map.clear();// 清理之前的图标
                        PoiOverlay poiOverlay = new PoiOverlay(map, poiItems);
                        poiOverlay.removeFromMap();
                        poiOverlay.addToMap();
                        poiOverlay.zoomToSpan();
                    }
                    if (searchType == 2) {

                    } else {

                    }

                }
            } else {

            }
        }
    }

    @Override
    public void onPoiItemSearched(PoiItem poiItem, int i) {

    }

    public class Myadapter extends FragmentPagerAdapter {

        public Myadapter(@NonNull FragmentManager fm) {
            super(fm);
        }

        @NonNull
        @Override
        public Fragment getItem(int position) {
            return fragmentList.get(position);
        }

        @Override
        public int getCount() {
            return fragmentList.size();
        }
    }

}